﻿using System.ComponentModel;
using Newtonsoft.Json;
using WeihanLi.Extensions;

namespace fabao.Common.Extensions
{
    public static class objectExtension
    {
        /// <summary>
        /// 将object转换为string，若转换失败，则返回""。不抛出异常。  
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ParseToString(this object obj)
        {
            try
            {
                if (obj == null)
                {
                    return string.Empty;
                }
                else
                {
                    return obj.ToString();
                }
            }
            catch
            {
                return string.Empty;
            }
        }
        /// <summary>
        /// 判断object是否为空
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool IsEmpty(this object value)
        {
            if (value != null && !string.IsNullOrEmpty(value.ParseToString()))
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 尝试将object转换为指定类型，若转换失败，则返回default(T)。不抛出异常。 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static T TryTo<T>(this object value)
        {
            if (value.IsEmpty())
                return default;

            try
            {
                Type type = typeof(T).Unwrap();
                Type type2 = value.GetType().Unwrap();
                if (type2 == type)
                {
                    return (T)value;
                }

                TypeConverter converter = TypeDescriptor.GetConverter(type2);
                if (converter.CanConvertTo(type))
                {
                    return (T)converter.ConvertTo(value, type);
                }

                converter = TypeDescriptor.GetConverter(type);
                if (converter.CanConvertFrom(type2))
                {
                    return (T)converter.ConvertFrom(value);
                }

                return JsonConvert.DeserializeObject<T>(value.ToJson());
            }
            catch
            {
                return default;
            }
        }
    }
}
